/*===============================================================
 *   Copyright (C) 2017 All rights reserved.
 *   
 *   文件名称：main.c
 *   创 建 者：陈迪林
 *   创建日期：2017年08月02日
 *   描    述：
 *
 *   更新日志：
 *
 ================================================================*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>
#include <dirent.h>
#include <time.h>
#include <sqlite3.h>
#include "lib.h"

int main(int argc,char *argv[]) 
{
    int pid = fork();
    if(pid > 0)
        exit(0);
    sqlite3 *db;
    
    char *errmsg;
    if(SQLITE_OK != sqlite3_open("sql_data.db", &db))
    {
        printf("Sqlite3 error : %s\n", sqlite3_errmsg(db));
        exit(-1);
    }

    sqlite3_exec(db, "create table user_info(name, passwd)", NULL, NULL , &errmsg);
    
    mkdir("userdir", 0666);
    
    int serversock = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == serversock)
    {
        perror("Socket");
        return -1;
    }

    int fd = open("log.txt", O_CREAT | O_WRONLY | O_APPEND, 0666);

    struct sockaddr_in addr={0},clienaddr={0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8888);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");

    int on = 1;
    setsockopt(serversock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);

    if(-1 == bind(serversock, (struct sockaddr *)&addr, sizeof addr))
    {
        perror("Bind");
        return -1;
    }

    listen(serversock,10);
    int len = sizeof clienaddr;
    int cliensock;
    char buff[500] = {0};
    time_t cur_time;
    while(1)
    {
        cliensock = accept(serversock, (struct sockaddr *)&clienaddr, &len);
    
        time(&cur_time);
        sprintf(buff, "time:%sip:%s\n\n",ctime(&cur_time), inet_ntoa(clienaddr.sin_addr));
        write(fd, buff, strlen(buff));

        pthread_t t;
        pthread_create(&t, NULL, thread_func, &cliensock);     

 //       thread_func(&cliensock);

        usleep(10);
   }

    return 0;
}
